<template>
  <div class="container">
    <!-- 页面名称 -->
    <div class="header">
      <span>系统角色</span>
    </div>

    <!-- 内容 -->
    <el-container class="body">
      <el-main class="mainmain">
        <div class="firsthe">
          <!-- 新增按钮及查询 -->
          <el-button
            type="primary"
            class="add"
            @click="onHandleAdd"
            :v-if="pageData.permissions.Add"
            >新增</el-button
          >

          <el-dialog
            :width="400"
            :title="pageData.editDialogTitle"
            v-model="pageData.editDialogVisible"
            destroy-on-close
            custom-class="editDialog-class"
          >
            <roleedit
              :modifyObj="pageData.tableParams.currentRow"
              :isAdd="pageData.isAdd"
              @Ok="onOk"
              @Cancel="() => (pageData.editDialogVisible = false)"
            />
          </el-dialog>

          <div class="search">
            <el-input
              v-model="pageData.queryParams.keyword"
              clearable
              placeholder="按编号/名称搜索"
              style="max-width: 180px"
              @blur="onHandleKeywordBlur"
              @clear="onHandleKeywordBlur"
              @keyup.enter="onHandleKeywordBlur"
              ><template #prepend>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>

            <el-button type="primary" plain @click="onHandleSearch"
              >搜索</el-button
            >
            <el-button type="warning" plain @click="onHandleReset"
              >重置</el-button
            >
          </div>
        </div>

        <el-row class="row-2">
          <!-- tabel -->
          <el-table
            ref="roleTable"
            class="role-table"
            row-key="fuserid"
            stripe
            border
            highlight-current-row
            v-loading="pageData.tableParams.tableLoading"
            :data="pageData.tableParams.tableData"
            @sort-change="tableSortFunc"
          >
            <!-- @current-change="(row) => (pageData.tableParams.currentRow = row)" -->
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="60"
            />
            <el-table-column
              prop="ffullname"
              label="角色名称"
              min-width="120"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              prop="fusername"
              label="角色编码"
              min-width="120"
              sortable="custom"
            >
            </el-table-column>
            <!-- <el-table-column
            prop="funittypeid"
            label="适用类型"
            width="80"
            align="center"
            show-overflow-tooltip
            :formatter="typeFormatter"
          >
          </el-table-column>
          <el-table-column
            prop="fpermission"
            label="权限"
            width="100"
            align="center"
            show-overflow-tooltip
            :formatter="permissionFormatter"
          >
          </el-table-column> -->
            <el-table-column
              prop="state"
              label="状态"
              width="60"
              align="center"
              show-overflow-tooltip
              :formatter="stateFormatter"
            >
            </el-table-column>
            <el-table-column
              prop="fcreatetime"
              label="录入时间"
              width="150"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              :v-if="
                pageData.permissions.Edit ||
                pageData.permissions.Del ||
                pageData.permissions.SetUc
              "
              label="操作"
              width="90"
              align="center"
              show-overflow-tooltip
            >
              <!-- <template #header>
              <span>操作</span>
            </template> -->
              <template #default="{ row }">
                <el-icon
                  :v-if="pageData.permissions.Edit"
                  title="编辑"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleEdit(row)"
                >
                  <Edit />
                </el-icon>
                <el-icon
                  :v-if="pageData.permissions.Del"
                  title="删除"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleDel(row.fuserid)"
                >
                  <Delete />
                </el-icon>
                <el-icon
                  :v-if="pageData.permissions.SetUc"
                  title="设置权限"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleSetUc(row)"
                >
                  <Unlock />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页查询 -->
          <el-col :span="24">
            <el-pagination
              style="margin-top: 20px"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="pageData.tableParams.pageSizeOptions"
              :current-page="pageData.queryParams.pageIndex"
              :page-size="pageData.queryParams.pageSize"
              :total="pageData.tableParams.total"
              @current-change="onHandleCurrentChange"
              @size-change="onHandleSizeChange"
            >
            </el-pagination>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <!-- 分配权限弹窗 -->
    <el-dialog
      :width="600"
      :title="pageData.ucDialogTitle"
      v-model="pageData.ucDialogVisible"
      destroy-on-close
      custom-class="editDialog-class"
    >
      <roleuc
        :modifyObj="pageData.tableParams.currentRow"
        @Ok="() => (pageData.ucDialogVisible = false)"
        @Cancel="() => (pageData.ucDialogVisible = false)"
      />
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, nextTick, reactive, ref, toRefs } from "vue";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import utils from "@/common/utils";
import enums from "@/common/enums";

import { queryRolePageList, deleteRole } from "@/api/system";
import roleedit from "./edit";
import roleuc from "./roleuc";

import {
  Edit,
  Delete,
  Unlock,
  UserFilled,
  Search,
} from "@element-plus/icons-vue";

export default {
  name: "RoleInfo",
  components: { roleedit, roleuc, Edit, Delete, Unlock, UserFilled, Search },
  setup(props, context) {
    onMounted(() => {
      nextTick(pageFunc.getTableData);
      // let st = null;
      // window.onresize = () => {
      //   return (() => {
      //     if (st) {
      //       clearTimeout(st);
      //       st = null;
      //     }
      //     st = setTimeout(() => {
      //       this.setPageHeight();
      //     }, 500);
      //   })();
      // };
    });

    const roleTable = ref();
    const pageState = reactive({
      pageData: {
        permissions: {
          Add: utils.checkPermission("sysrole_add"),
          Del: utils.checkPermission("sysrole_delete"),
          Edit: utils.checkPermission("sysrole_edit"),
          SetUc: utils.checkPermission("sysrole_setuc"),
        },
        typeEnumObj: enums.OrgTypeEnum,
        permissionEnumObj: enums.PermissionEnum,
        stateEnumObj: enums.StateEnum,
        screenHeight: 0,
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
          sortFields: "",
          sortOrder: enums.SortEnum.Asc.key,
          keyword: "",
          state: enums.StateEnum.Delete.value,
        },
        tableParams: {
          tableLoading: false,
          tableHeight: 0,
          // tableColumns: [],
          pageSizeOptions: ["10", "15", "30", "50", "100", "200"],
          total: 0,
          tableData: [],
          multipleSelection: [],
          currentRow: {},
        },

        editDialogTitle: "角色",
        editDialogVisible: false,
        isAdd: false,
        ucDialogTitle: "分配操作",
        ucDialogVisible: false,
      },
    });
    const pageFunc = {
      getTableData: () => {
        pageState.pageData.tableParams.currentRow = {};
        pageState.pageData.tableParams.tableLoading = true;
        queryRolePageList(pageState.pageData.queryParams)
          .then((ret) => {
            console.log("查询角色列表", ret);
            pageState.pageData.tableParams.tableData = ret.data;
            pageState.pageData.tableParams.total = ret.recordsTotal;
            pageState.pageData.tableParams.tableLoading = false;
          })
          .catch((error) => {
            ElMessage.error(error.message || "请求出错");
            pageState.pageData.tableParams.tableLoading = false;
          });
      },
      tableSortFunc: ({ column, prop, order }) => {
        pageState.pageData.queryParams.sortFields = prop;
        if (!utils.isEmpty(order) && order === "ascending") {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Asc.key;
        } else if (!utils.isEmpty(order) && order === "descending") {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Desc.key;
        } else {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Asc.key;
        }
        pageFunc.getTableData();
      },
      typeFormatter: (row, column, cellValue, index) => {
        return pageState.pageData.typeEnumObj.getLabelByValue(cellValue);
      },
      permissionFormatter: (row, column, cellValue, index) => {
        return pageState.pageData.permissionEnumObj.getLabelByValue(cellValue);
      },
      stateFormatter: (row, column, cellValue, index) => {
        return pageState.pageData.stateEnumObj.getLabelByValue(cellValue);
      },
      // 模糊查询
      onHandleSearch: () => {
        pageFunc.getTableData();
      },
      onHandleReset: () => {
        pageState.pageData.queryParams.keyword = "";
        pageFunc.getTableData();
      },
      onHandleKeywordBlur: () => {
        pageState.pageData.queryParams.pageIndex = 1;
        pageFunc.getTableData();
      },
      onHandleCurrentChange: (e) => {
        pageState.pageData.queryParams.pageIndex = e;
        pageFunc.getTableData();
      },
      onHandleSizeChange: (e) => {
        pageState.pageData.queryParams.pageIndex = 1;
        pageState.pageData.queryParams.pageSize = e;
        pageFunc.getTableData();
      },
      onHandleAdd: () => {
        pageState.pageData.editDialogTitle = "新增";
        pageState.pageData.editDialogVisible = true;
        pageState.pageData.isAdd = true;
      },
      // 编辑测通
      onHandleEdit: (row) => {
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.tableParams.currentRow = row;
        pageState.pageData.editDialogTitle = "编辑";
        pageState.pageData.editDialogVisible = true;
        pageState.pageData.isAdd = false;
      },
      onHandleDel: (id) => {
        if (utils.isEmpty(id)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        ElMessageBox.confirm("此操作将删除该角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const loading = ElLoading.service({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)",
            });
            // 删除测通
            deleteRole(id)
              .then((res) => {
                console.log("删除角色", res);
                loading.close();
                ElMessage.success("删除成功");
                pageFunc.getTableData();
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          })
          .catch(() => {});
      },
      onOk: ({ isAdd, retObj }) => {
        pageState.pageData.isAdd = isAdd;
        pageState.pageData.editDialogVisible = false;
        pageFunc.getTableData();
      },
      onHandleSetUc: (row) => {
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.tableParams.currentRow = row;
        pageState.pageData.ucDialogTitle = "分配操作";
        pageState.pageData.ucDialogVisible = true;
      },
    };

    return {
      roleTable,
      ...toRefs(pageState),
      ...pageFunc,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 0;
  margin: 0;
  .header {
    width: 100%;
    background-color: white;
    user-select: none;

    text-align: left;
    span {
      line-height: 50px;
      font-size: 18px;
      font-weight: 700;
      text-align: left;
      margin-left: 20px;
    }
  }

  .body {
    margin-top: 20px;
    background-color: white;
    height: 77vh;
    // 树形下拉框
    .mainaside {
      background-color: rgb(230, 240, 250);
      border-right: 1px solid #ccc;
      .user_tree {
        .el-tree {
          border-bottom: 1px solid #ddd;
        }
      }
    }
    // 内容表格
    .mainmain {
      .firsthe {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .search {
          display: flex;
          align-items: center;
          user-select: none;

          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>

<style>
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.el-dialog .el-dialog__header {
  padding: 20px 0;
  padding-left: 20px;
  margin: 0;

  word-break: break-all;
  border-bottom: 1px solid #ddd;
  text-align: left;
}

.el-select {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-select .el-option {
  width: 100%;
  border: none;
  border-radius: 0;
}
</style>
